package com.ohuang.jiaxiaotong.Activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.example.myhttp.CallBackString;
import com.example.myhttp.Ihttp;
import com.ohuang.jiaxiaotong.MyHttpURL;
import com.ohuang.jiaxiaotong.R;
import com.ohuang.jiaxiaotong.Util.Ohuang;
import com.ohuang.jiaxiaotong.Util.Sys;
import com.ohuang.jiaxiaotong.base.BaseAc;
import com.ohuang.jiaxiaotong.entity.ClassEntity;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;

public class JoinClassActivity extends BaseAc {
    private ListView listView;
    private List<ClassEntity> mData;
    private CommonAdapter commonAdapter;
    private SearchView searchView;
    private final static int JOIN_OK = 1, JOIN_ERROR = 2, NET_ERROR = 3, NET_OTHER = 4;
    private String className;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_join_class);

        setTitle("加入班级");
        Ohuang.changeStatusBarTextImgColor(this, true);
        Objects.requireNonNull(getSupportActionBar()).setHomeAsUpIndicator(R.mipmap.icon_goback);//设置ActionBar返回按钮


        listView = findViewById(R.id.listView_JoinClass);
        searchView = findViewById(R.id.search_joinclass);
        searchView.setSubmitButtonEnabled(true);
//设置搜索框直接展开显示。左侧有放大镜(在搜索框中) 右侧有叉叉 可以关闭搜索框
        //   searchView.setIconified(false);
        //设置搜索框直接展开显示。左侧有无放大镜(在搜索框中) 右侧无叉叉 有输入内容后有叉叉 不能关闭搜索框
//        searchView.onActionViewExpanded();
        //设置搜索框直接展开显示。左侧有放大镜(在搜索框外) 右侧无叉叉 有输入内容后有叉叉 不能关闭搜索框
        searchView.setIconifiedByDefault(false);

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                if (Sys.isClick()) {
                    HttpGetClass(query);
                    className = query;
                }
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });
        httpGetAllClass();//获取所有班级

    }

    //搜索该班级
    private void HttpGetClass(String className) {

        HashMap<String,String> map=new HashMap<>();
        map.put("className", className);
        Ihttp.getInstance().post(MyHttpURL.mainUrl + "user/findClassName", map, new CallBackString() {
            @Override
            public void success(String ojb) {
                String code = ojb;
                if ("success".equals(code)) {
                    myHandler.sendEmptyMessage(JOIN_OK);
                } else if ("error".equals(code)) {
                    myHandler.sendEmptyMessage(JOIN_ERROR);
                } else {
                    myHandler.sendEmptyMessage(NET_OTHER);
                }
            }


            @Override
            public void fail(String s) {
                myHandler.sendEmptyMessage(NET_ERROR);
            }
        });


    }

    @SuppressLint("HandlerLeak")
    private Handler myHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case NET_ERROR:
                    Toast.makeText(JoinClassActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                    break;
                case NET_OTHER:
                    Toast.makeText(JoinClassActivity.this, "返回值错误", Toast.LENGTH_SHORT).show();
                    break;
                case JOIN_OK:
                    Intent intent = new Intent(JoinClassActivity.this, JoinClassmemberActivity.class);
                    intent.putExtra("className", className);
                    startActivity(intent);
                    break;
                case JOIN_ERROR:
                    Toast.makeText(JoinClassActivity.this, "未找到该班级", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    public boolean onOptionsItemSelected(MenuItem item) {

        if (item.getItemId() == android.R.id.home) {//左上角返回按钮
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    //查询所有班级
    private void httpGetAllClass() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(MyHttpURL.mainUrl+"user/"  )
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        GithubService service = retrofit.create(GithubService.class);

        service.getAllClass().enqueue(new Callback<List<ClassEntity>>() {
            @Override
            public void onResponse(Call<List<ClassEntity>> call, Response<List<ClassEntity>> response) {
                mData = response.body();
                if (mData != null) {
                    commonAdapter = new CommonAdapter(JoinClassActivity.this, R.layout.list_class, mData) {
                        @Override
                        protected void convert(ViewHolder viewHolder, final Object item, int position) {
                            viewHolder.setText(R.id.txt_listClass, "班级名：" + ((ClassEntity) item).getClassName());

                        }
                    };
                    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            if (Sys.isClick()) {
                                Intent intent = new Intent(JoinClassActivity.this, JoinClassmemberActivity.class);
                                intent.putExtra("className", mData.get(position).getClassName());
                                startActivity(intent);
                            }
                        }
                    });
                    listView.setAdapter(commonAdapter);
                }
            }

            @Override
            public void onFailure(Call<List<ClassEntity>> call, Throwable t) {

            }
        });
    }


    interface GithubService {

        @GET("findAllClass")
        Call<List<ClassEntity>> getAllClass();
    }
}
